package chapter6_2_condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author huayuhao
 * @date 2020/12/17 15:38
 */
public class ConditionTest {



    public static void main(String[] args) throws InterruptedException {

        // 基于AQS实现
        ReentrantLock lock = new ReentrantLock();
        // 创建lock对象的condition条件变量  AQS中的ConditionObject内部类,可以访问内部的state,每个条件变量内部维护了一个条件队列
        Condition condition = lock.newCondition();
        Thread thread = new Thread(()->{
            // 获取独占锁
            lock.lock();
            try {
                System.out.println("begin wait");
                // 阻塞当前线程
                condition.await();
                System.out.println("end wait");
            }catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        });
        // 启动线程
        thread.start();
        // 主线程先睡3s
        Thread.sleep(3000);
        lock.lock();
        System.out.println("begin signal");
        condition.signal();
        System.out.println("end signal");
        lock.unlock();
    }

}
